package com.csdig.cms.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.csdig.db.model.Pagination;

public class PageUtils {

	public static Integer getPageNo(Integer page) {
		return (page == null || page.intValue() == 0 ? Integer.valueOf(1) : page);
	}

	public static Integer getPageSize(Integer rows) {
		return ((rows == null || rows.intValue() == 0) ? Integer.valueOf(10) : rows);
	}

	public static Map<String, Object> toMap(Pagination<?> pag) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", pag.getCount());
		if (pag.getList() != null) {
			map.put("rows", pag.getList());
		} else {
			map.put("rows", new ArrayList<Object>());
		}
		List<?> footers = pag.getFooter();
		if (footers != null) {
			map.put("footer", footers);
		}
		return map;
	}

	public static String generatePageLink() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return sdf.format(new Date()) + new Random().nextInt(10);
	}

	public static String getDes(String srcDes) {
		String[] strs = srcDes.split("\n");
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < strs.length; i++) {
			String temp = strs[i].replaceAll("\n", "");
			if (temp.trim().length() == 0)
				continue;
			result.append("<p>").append(temp).append("</p>");
			if (i == strs.length - 1) {
				result.append("<br/>");
			}
		}
		return result.toString();
	}

	public static String reservDes(String srcDes) {
		return srcDes.replaceAll("<br/>", "\n").replaceAll("<p>", "").replaceAll("</p>", "");
	}

	public static String resoleLazyImg(String orginContent) throws Exception {
		if (StringUtils.isNotEmpty(orginContent)) {
			String domain = FrontUtils.getDomain();
			Document document = Jsoup.parse(orginContent, domain);
			Elements imgElements = document.getElementsByTag("img");
			for (int i = 0; i < imgElements.size(); i++) {
				Element image = imgElements.get(i);
				String imgSrc = image.attr("data-original");
				if(StringUtils.isNotEmpty(imgSrc)){
					image.attr("src",imgSrc);
				}
			}
			return document.body().html();

		}
		return null;
	}

}
